import BasicController from './../BasicController'
import ErrorHandlerCode from './../../util/ErrorHandlerCode'

import multiparty from 'multiparty'
import fs from 'fs'
import os from 'os'
import path from 'path'
import util from 'util'

class FileAdminController extends BasicController{
    insertImage(req,res){
        //根据ip和时间戳重新构造上传图片名字
        const _name = req.files.image.originalFilename;
        let fileName = req.ip + req.body.timestamp;
        fileName = new Buffer(fileName).toString('base64');

        let type = req.files.image.type;
        let extension_name  = '';
        switch (type) {   //判断文件类型  
            case 'image/pjpeg': extension_name = '.jpg';  break;  
            case 'image/jpeg': extension_name = '.jpg'; break;  
            case 'image/gif': extension_name = '.gif'; break;  
            case 'image/png': extension_name = '.png'; break;  
            case 'image/x-png': extension_name = '.png'; break;  
            case 'image/bmp': extension_name = '.bmp'; break;
            default:if(_name.indexOf('.')<=0)
                        return;
                    else {
                        let _tmp = _name.split('.');
                        extension_name = _tmp[_tmp.length-1];
                        break;
                    }   
        } 
        let realPath = path.join(__dirname,'../../public/upload/'+fileName+extension_name);
        let uploadPath = req.files.image.path;

        let is = fs.createReadStream(uploadPath);
        let os = fs.createWriteStream(realPath);
        is.pipe(os);
        is.on('end',function() {
            fs.unlinkSync(uploadPath);
            const IP = serverIP();
            const data = {
                status:0,
                url: IP+":3000/upload/"+fileName+extension_name
            }
            res.json(data);
        });
        is.on('error',function(err) {
            res.json(ErrorHandlerCode.UPLOADIMGERROE);
        });
    }
}

function serverIP(){
        let IPv4;
        //MAC 上获取IP
        // for(let i=0; i<os.networkInterfaces().en0.length; i++){  
        //     if(os.networkInterfaces().en0[i].family === 'IPv4'){  
        //         IPv4=os.networkInterfaces().en0[i].address;  
        //     }  
        // }  
 
        //ubuntu server上获取IP
        // for(let i=0; i<os.networkInterfaces().eth0.length; i++){  
        //     if(os.networkInterfaces().eth0[i].family === 'IPv4'){  
        //         IPv4 = os.networkInterfaces().eth0[i].address;  
        //     }  
        // }

        //windows上获取IP
        for(let i=0; i<os.networkInterfaces().WLAN.length; i++){  
            if(os.networkInterfaces().WLAN[i].family === 'IPv4'){  
                IPv4 = os.networkInterfaces().WLAN[i].address;  
            }  
        }
        return IPv4; 
    }

module.exports = new FileAdminController();